<template>
  <div class="goodsDia">
    <el-dialog :title="this.isAdd ? '添加商品' : '修改商品'" center :visible.sync="isShow" :before-close="cancel"
      @opened="createEditor">
      <el-form ref="goodsForm" :model="form" :rules="rules">
        <el-form-item prop="first_cateid" label="一级分类" :label-width="formLabelWidth">
          <el-select v-model="form.first_cateid" @change="first_change(false)" placeholder="请选择">
            <el-option v-for="item in getCate" :key="item.id" :label="item.catename" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="second_cateid" label="二级分类" :label-width="formLabelWidth">
          <el-select v-model="form.second_cateid" placeholder="请选择">
            <el-option v-for="item in second_attrs" :key="item.id" :label="item.catename" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="goodsname" label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="form.goodsname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="price" label="价格" :label-width="formLabelWidth">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="market_price" label="市场价格" :label-width="formLabelWidth">
          <el-input v-model="form.market_price" autocomplete="off"></el-input>
        </el-form-item>
        <!-- 图片上传upload -->
        <el-form-item label="图片" :label-width="formLabelWidth">
          <el-upload action="#" :auto-upload="false" :on-preview="onPreview" :on-remove="onRemove" :on-change="onChange"
            :file-list="fileList" :on-exceed="headleExceed" :limit="1" list-type="picture-card">
            <!-- :on-preview="handlePictureCardPreview" :on-remove="handleRemove" -->
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item prop="specsid" label="商品规格" :label-width="formLabelWidth">
          <el-select @change="specsChange(false)" v-model="form.specsid" placeholder="请选择">
            <el-option v-for="item in specs_Change" :key="item.id" :label="item.specsname" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="specsattr" label="规格属性" :label-width="formLabelWidth">
          <el-select v-model="form.specsattr" placeholder="请选择" multiple>
            <el-option v-for="item in specs_Attrs" :label="item" :key="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品" :label-width="formLabelWidth">
          <el-radio v-model="form.isnew" :label="1">是</el-radio>
          <el-radio v-model="form.isnew" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="是否热卖" :label-width="formLabelWidth">
          <el-radio v-model="form.ishot" :label="1">是</el-radio>
          <el-radio v-model="form.ishot" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch v-model="form.status" active-color="#13ce66" inactive-color="gray" :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
        <el-form-item label="商品介绍" :label-width="formLabelWidth">
          <div id="editor"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { goodsadd, specslist, goodsinfo, goodsedit } from "@/request/api";
import { mapActions, mapGetters } from "vuex";
import E from "wangeditor"
export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      // first_cateid一级分类编号second_cateid二级分类编号goodsname商品名称price商品价格market_price市场价格img商品图片（文件）description商品描述specsid商品规格编号specsattr商品规格属性isnew是否新品     1-是 2-否ishot是否热卖推荐 1-是 2-否status状态1正常2禁用
      form: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        img: "", //商品图片
        market_price: "",
        description: "",          //商品描述
        specsid: "",
        specsattr: "",
        isnew: 1,
        ishot: 1,
        status: 1,
      },
      //二级分类数据
      second_attrs: [],
      //二级规格数据
      specs_Change: [],   //商品规格
      specs_Attrs: [],    //规格数据
      rules: {
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        first_cateid: [
          { required: true, message: "请选择一级分类", trigger: "blur" },
        ],
        second_cateid: [
          { required: true, message: "请选择二级分类", trigger: "blur" },
        ],
        specsid: [
          { required: true, message: "请选择商品规格", trigger: "blur" },
        ],
        specsattr: [
          { required: true, message: "请选择商品规格", trigger: "blur" },
        ],
        price: [
          { required: true, message: "请输入价格", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        market_price: [
          { required: true, message: "请输入市场价格", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      formLabelWidth: "120px",
      //图片
      fileList: [],
      editor: null,   //编辑器初始值
    };
  },
  computed: {
    ...mapGetters({
      //分类数据
      getCate: "shop/getCate",
    }),
  },
  props: ["isShow", "isAdd"],
  mounted() {
    this.getCateAction();
    this.getSpecs();
  },
  methods: {
    //封装一个创建编辑器的方法
    createEditor() {
      this.editor = new E('#editor')
      //创建
      this.editor.create()
      //赋值初始值
      this.editor.txt.html(this.form.description)

    },
    ...mapActions({
      //分类数据
      getCateAction: "shop/getCateAction",
      //商品管理列表数据获取
      getGoodsAction: 'goods/getGoodsAction',
      //获取商品总数
      getCountGoodAction: 'goods/getCountGoodAction',
    }),
    //一级分类  选中  给二级分类赋值
    first_change(n) {
      let result = this.getCate.findIndex((item) => {
        return item.id == this.form.first_cateid;
      });
      this.second_attrs = this.getCate[result].children;
      if (!n) {
        //清空二级分类双向数据绑定值
        this.form.second_cateid = "";
      }
    },
    //一级规格数据
    getSpecs() {
      specslist().then((res) => {
        this.specs_Change = res.list;
      });
    },
    //二级规格数据
    specsChange(n) {
      let result = this.specs_Change.findIndex((item) => {
        return item.id == this.form.specsid;
      });
      this.specs_Attrs = this.specs_Change[result].attrs;
      if (!n) {
        //清空
        this.form.specsattr = "";
      }

    },
    //取消按钮
    cancel() {
      this.$emit("cancel");
      this.reset();
    },
    //  关闭dialog  清空表单  并移除校验结果
    reset() {
      this.form = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        img: "", //商品图片
        market_price: "",
        description: "",          //商品描述
        specsid: "",
        specsattr: "",
        isnew: 1,
        ishot: 1,
        status: 1,
      };
      this.$refs.goodsForm.resetFields();
      //删除上传的图片
      this.fileList = []
      //销毁编辑器
      this.editor.destroy()
    },
    //确定  提交表单按钮
    confirm() {
      this.$refs.goodsForm.validate((val) => {
        if (val) {
          this.form.specsattr = this.form.specsattr.join(",")
          this.form.description = this.editor.txt.html()
          if (this.isAdd) {
            //是一个添加接口
            goodsadd(this.form).then((res) => {
              if (res.code == 200) {
                this.$message.success(res.msg)
                //重新获取列表
                this.getGoodsAction()
                //获取商品总数
                this.getCountGoodAction()
                //关闭dialog弹框
                this.cancel()
              } else {
                this.$message.error(res.msg)
              }
            });
          } else {
            //是一个编辑接口
            console.log(this.form);
            goodsedit(this.form).then((res) => {
              // console.log(this.form);
              if (res.code == 200) {
                this.$message.success(res.msg)
                //重新获取列表
                this.getGoodsAction()
                //获取商品总数
                this.getCountGoodAction()
                //关闭弹框
                this.cancel()

              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      });
    },
    //数据回显
    lookup(id) {
      goodsinfo({ id }).then(res => {
        if (res.code == 200) {
          // console.log(res.list.price);
          this.form = res.list
          this.form.id = id
          this.form.price = res.list.price.toString()
          this.form.market_price = res.list.market_price.toString()
          //规格属性回显
          this.specs_Attrs = res.list.specsattr.split(",")
          this.form.specsattr = res.list.specsattr.split(",")
          //图片回显
          this.fileList = this.form.img ? [{ url: this.form.img }] : []
          this.first_change(true)
          this.specsChange(true)
          //调用接口
          this.getCateAction()
          this.getGoodsAction()
          //给富文本编辑器设置内容
          this.editor.txt.html(this.form.description)
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    //图片上传的事件
    onPreview(file) {    //图片预览
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    onRemove(file, fileList) {
      //隐藏预览
      this.dialogVisible = false
    },
    //图片改变时发生的变化
    onChange(file, fileList) {
      this.form.img = file.raw
    },
    headleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
        } 个文件`
      );
    }
  },
};
</script>
<style scoped></style>